<template>
  <div class="merchant-detail">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>商家详情</span>
          <div class="header-actions">
            <el-button @click="$router.back()">返回</el-button>
            <el-button
              v-if="canReview && merchantInfo.status === 'pending'"
              type="primary"
              @click="handleReview"
            >
              审核
            </el-button>
            <el-button
              v-if="canManageAccount"
              :type="merchantInfo.status === 'disabled' ? 'success' : 'danger'"
              @click="handleStatusChange"
            >
              {{ merchantInfo.status === 'disabled' ? '启用' : '禁用' }}
            </el-button>
          </div>
        </div>
      </template>

      <el-tabs v-model="activeTab">
        <!-- 基本信息 -->
        <el-tab-pane label="基本信息" name="basic">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="商家名称">
              {{ merchantInfo.name }}
            </el-descriptions-item>
            <el-descriptions-item label="联系人">
              {{ merchantInfo.contact }}
            </el-descriptions-item>
            <el-descriptions-item label="联系电话">
              {{ merchantInfo.phone }}
            </el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag :type="getStatusType(merchantInfo.status)">
                {{ getStatusText(merchantInfo.status) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="地址" :span="2">
              {{ merchantInfo.address }}
            </el-descriptions-item>
            <el-descriptions-item label="营业执照" :span="2">
              <el-image
                v-if="merchantInfo.license"
                :src="merchantInfo.license"
                :preview-src-list="[merchantInfo.license]"
                fit="contain"
                style="width: 200px; height: 200px"
              />
              <span v-else>暂无</span>
            </el-descriptions-item>
            <el-descriptions-item label="创建时间">
              {{ merchantInfo.createTime }}
            </el-descriptions-item>
            <el-descriptions-item label="更新时间">
              {{ merchantInfo.updateTime }}
            </el-descriptions-item>
          </el-descriptions>
        </el-tab-pane>

        <!-- 账户信息 -->
        <el-tab-pane label="账户信息" name="account">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="账户余额">
              ¥{{ accountInfo.balance?.toFixed(2) || '0.00' }}
            </el-descriptions-item>
            <el-descriptions-item label="账户状态">
              <el-tag :type="accountInfo.status === 'active' ? 'success' : 'danger'">
                {{ accountInfo.status === 'active' ? '正常' : '冻结' }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="累计收入">
              ¥{{ accountInfo.totalIncome?.toFixed(2) || '0.00' }}
            </el-descriptions-item>
            <el-descriptions-item label="累计支出">
              ¥{{ accountInfo.totalExpense?.toFixed(2) || '0.00' }}
            </el-descriptions-item>
          </el-descriptions>

          <div class="account-actions" v-if="canSettlement && accountInfo.balance > 0">
            <el-button
              :type="accountInfo.status === 'active' ? 'danger' : 'success'"
              @click="handleAccountStatusChange"
            >
              {{ accountInfo.status === 'active' ? '冻结账户' : '解冻账户' }}
            </el-button>
            <el-button type="primary" @click="handleSettlement">
              申请结算
            </el-button>
          </div>
        </el-tab-pane>

        <!-- 结算记录 -->
        <el-tab-pane label="结算记录" name="settlement">
          <el-table
            v-loading="settlementLoading"
            :data="settlementRecords"
            border
            style="width: 100%"
          >
            <el-table-column prop="id" label="结算单号" width="180" />
            <el-table-column prop="amount" label="结算金额" width="120">
              <template #default="{ row }">
                ¥{{ row.amount?.toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="getSettlementStatusType(row.status)">
                  {{ getSettlementStatusText(row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="申请时间" width="180" />
            <el-table-column prop="reviewTime" label="审核时间" width="180" />
            <el-table-column prop="remark" label="备注" show-overflow-tooltip />
          </el-table>

          <div class="pagination">
            <el-pagination
              v-model:current-page="settlementPage"
              v-model:page-size="settlementPageSize"
              :total="settlementTotal"
              :page-sizes="[10, 20, 50]"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSettlementSizeChange"
              @current-change="handleSettlementCurrentChange"
            />
          </div>

          <div class="export-actions" v-if="canSettlement">
            <el-button
              type="primary"
              link
              @click="handleExport"
            >
              导出记录
            </el-button>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 审核对话框 -->
    <el-dialog
      v-model="reviewDialogVisible"
      title="商家审核"
      width="500px"
    >
      <el-form
        ref="reviewFormRef"
        :model="reviewForm"
        :rules="reviewRules"
        label-width="100px"
      >
        <el-form-item label="审核结果" prop="status">
          <el-radio-group v-model="reviewForm.status">
            <el-radio label="approved">通过</el-radio>
            <el-radio label="rejected">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核意见" prop="comment">
          <el-input
            v-model="reviewForm.comment"
            type="textarea"
            :rows="4"
            placeholder="请输入审核意见"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="reviewDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitReview">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 结算对话框 -->
    <el-dialog
      v-model="settlementDialogVisible"
      title="申请结算"
      width="500px"
    >
      <el-form
        ref="settlementFormRef"
        :model="settlementForm"
        :rules="settlementRules"
        label-width="100px"
      >
        <el-form-item label="结算金额" prop="amount">
          <el-input-number
            v-model="settlementForm.amount"
            :min="0"
            :max="accountInfo.balance"
            :precision="2"
            :step="100"
            style="width: 200px"
          />
          <span class="form-tip">可结算余额：¥{{ accountInfo.balance?.toFixed(2) }}</span>
        </el-form-item>
        <el-form-item label="结算账户" prop="account">
          <el-input
            v-model="settlementForm.account"
            placeholder="请输入结算账户"
          />
        </el-form-item>
        <el-form-item label="开户行" prop="bank">
          <el-input
            v-model="settlementForm.bank"
            placeholder="请输入开户行"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="settlementForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="settlementDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitSettlement">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getMerchantDetail,
  getMerchantAccount,
  getMerchantSettlementRecords,
  reviewMerchantSettlement,
  updateMerchantAccountStatus,
  merchantSettlement,
  exportSettlementRecords
} from '@/api/merchant'
import { checkPermission } from '@/permission'

const route = useRoute()
const router = useRouter()
const merchantId = route.params.id

// 标签页
const activeTab = ref('basic')

// 商家信息
const merchantInfo = ref({})

// 账户信息
const accountInfo = ref({})

// 结算记录
const settlementLoading = ref(false)
const settlementRecords = ref([])
const settlementPage = ref(1)
const settlementPageSize = ref(10)
const settlementTotal = ref(0)

// 审核相关
const reviewDialogVisible = ref(false)
const reviewFormRef = ref(null)
const reviewForm = reactive({
  status: 'approved',
  comment: ''
})

const reviewRules = {
  status: [
    { required: true, message: '请选择审核结果', trigger: 'change' }
  ],
  comment: [
    { required: true, message: '请输入审核意见', trigger: 'blur' },
    { min: 5, max: 200, message: '长度在 5 到 200 个字符', trigger: 'blur' }
  ]
}

// 结算相关
const settlementDialogVisible = ref(false)
const settlementFormRef = ref(null)
const settlementForm = reactive({
  amount: 0,
  account: '',
  bank: '',
  remark: ''
})

const settlementRules = {
  amount: [
    { required: true, message: '请输入结算金额', trigger: 'blur' },
    { type: 'number', min: 0, message: '结算金额必须大于0', trigger: 'blur' }
  ],
  account: [
    { required: true, message: '请输入结算账户', trigger: 'blur' },
    { pattern: /^[\d]{16,19}$/, message: '请输入正确的银行账号', trigger: 'blur' }
  ],
  bank: [
    { required: true, message: '请输入开户行', trigger: 'blur' }
  ]
}

// 权限控制
const canReview = computed(() => checkPermission('merchant', 'review'))
const canSettlement = computed(() => checkPermission('merchant', 'settlement'))
const canManageAccount = computed(() => checkPermission('merchant', 'account'))

// 获取商家详情
const getDetail = async () => {
  try {
    const data = await getMerchantDetail(merchantId)
    merchantInfo.value = data
  } catch (error) {
    console.error('获取商家详情失败:', error)
  }
}

// 获取账户信息
const getAccount = async () => {
  try {
    const data = await getMerchantAccount(merchantId)
    accountInfo.value = data
  } catch (error) {
    console.error('获取账户信息失败:', error)
  }
}

// 获取结算记录
const getSettlementRecords = async () => {
  settlementLoading.value = true
  try {
    const { data, total } = await getMerchantSettlementRecords(merchantId, {
      page: settlementPage.value,
      pageSize: settlementPageSize.value
    })
    settlementRecords.value = data
    settlementTotal.value = total
  } catch (error) {
    console.error('获取结算记录失败:', error)
  } finally {
    settlementLoading.value = false
  }
}

// 处理审核
const handleReview = () => {
  reviewDialogVisible.value = true
  reviewForm.status = 'approved'
  reviewForm.comment = ''
}

// 提交审核
const submitReview = async () => {
  if (!reviewFormRef.value) return
  
  try {
    await reviewFormRef.value.validate()
    await reviewMerchantSettlement(merchantId, reviewForm)
    ElMessage.success('审核成功')
    reviewDialogVisible.value = false
    getDetail()
  } catch (error) {
    console.error('提交审核失败:', error)
  }
}

// 处理账户状态变更
const handleAccountStatusChange = async () => {
  const newStatus = accountInfo.value.status === 'active' ? 'frozen' : 'active'
  const actionText = newStatus === 'active' ? '解冻' : '冻结'
  
  try {
    await ElMessageBox.confirm(
      `确认要${actionText}该商家账户吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await updateMerchantAccountStatus(merchantId, { status: newStatus })
    ElMessage.success(`${actionText}成功`)
    getAccount()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('修改账户状态失败:', error)
    }
  }
}

// 处理结算
const handleSettlement = () => {
  settlementDialogVisible.value = true
  settlementForm.amount = accountInfo.value.balance || 0
  settlementForm.account = ''
  settlementForm.bank = ''
  settlementForm.remark = ''
}

// 提交结算
const submitSettlement = async () => {
  if (!settlementFormRef.value) return
  
  try {
    await settlementFormRef.value.validate()
    await merchantSettlement(merchantId, settlementForm)
    ElMessage.success('申请结算成功')
    settlementDialogVisible.value = false
    getAccount()
    getSettlementRecords()
  } catch (error) {
    console.error('提交结算失败:', error)
  }
}

// 结算记录分页
const handleSettlementSizeChange = (val) => {
  settlementPageSize.value = val
  getSettlementRecords()
}

const handleSettlementCurrentChange = (val) => {
  settlementPage.value = val
  getSettlementRecords()
}

// 导出结算记录
const handleExport = async () => {
  try {
    const response = await exportSettlementRecords(merchantId)
    const blob = new Blob([response], { type: 'application/vnd.ms-excel' })
    const link = document.createElement('a')
    link.href = window.URL.createObjectURL(blob)
    link.download = `结算记录_${merchantInfo.value.name}_${new Date().toLocaleDateString()}.xlsx`
    link.click()
    window.URL.revokeObjectURL(link.href)
  } catch (error) {
    console.error('导出失败:', error)
  }
}

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    pending: 'warning',
    approved: 'success',
    rejected: 'danger',
    disabled: 'info'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    pending: '待审核',
    approved: '已通过',
    rejected: '已拒绝',
    disabled: '已禁用'
  }
  return statusMap[status] || '未知'
}

// 获取结算状态类型
const getSettlementStatusType = (status) => {
  const statusMap = {
    pending: 'warning',
    approved: 'success',
    rejected: 'danger',
    completed: 'info'
  }
  return statusMap[status] || 'info'
}

// 获取结算状态文本
const getSettlementStatusText = (status) => {
  const statusMap = {
    pending: '待审核',
    approved: '已通过',
    rejected: '已拒绝',
    completed: '已完成'
  }
  return statusMap[status] || '未知'
}

onMounted(() => {
  getDetail()
  getAccount()
  getSettlementRecords()
})
</script>

<style lang="scss" scoped>
.merchant-detail {
  padding: 20px;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .header-actions {
      display: flex;
      gap: 10px;
    }
  }

  .account-actions {
    margin-top: 20px;
    display: flex;
    gap: 10px;
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }

  .export-actions {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }

  .form-tip {
    margin-left: 10px;
    color: var(--text-secondary);
    font-size: 14px;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 